package com.wstuo.common.config.category.dao;
import java.util.List;
import org.hibernate.FetchMode;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.wstuo.common.config.category.dto.CategoryDTO;
import com.wstuo.common.config.category.entity.CICategory;
import com.wstuo.common.config.category.entity.Category;
import com.wstuo.common.dao.BaseDAOImplHibernate;

/**
 * ConfigurationItemsDAO Bean 2010.9.13
 *
 * @author spring
 *
 */
public class CICategoryDAO extends BaseDAOImplHibernate<CICategory>
    implements ICICategoryDAO
{
	private CICategory ciCategory = null;
    /**
     * find all ConfigurationItems
     * @param dtype
     * @return List<ConfigurationItems>
     */
    @SuppressWarnings( "unchecked" )
    public List<CICategory> findConfigurationItems(String dtype){
        String hql = "from CICategory c where c.parent IS NULL and categoryRoot = '" + dtype + "' and dataFlag!=99 order by c.cno asc";
        return getHibernateTemplate().find( hql );
    }
    
    /**
     * 查询配置项分类树
     * @param dtype
     * @return CICategory
     */
    @SuppressWarnings("unchecked")
    public CICategory findConfigureItemTree(String dtype){
    	final DetachedCriteria dc = DetachedCriteria.forClass(CICategory.class);

    	dc.createAlias("children","children", DetachedCriteria.LEFT_JOIN);
    	dc.setFetchMode("children",FetchMode.JOIN );

    	dc.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    	dc.add(Restrictions.eq("categoryRoot", dtype));
    	
    	List<CICategory> list = getHibernateTemplate().findByCriteria(dc);
    	
    	if(list!=null && list.size()>0)
    		ciCategory = list.get(0);
    	
    	return ciCategory;
    }
    /**
     * 查询配置项分类树
     * @param parentEventId
     * @return CICategory
     */
    @SuppressWarnings("unchecked")
    public CICategory findConfigureItemTreeByParentEventId(Long parentEventId){
    	
    	final DetachedCriteria dc = DetachedCriteria.forClass(CICategory.class);

    	dc.createAlias("children","children", DetachedCriteria.LEFT_JOIN);
    	dc.setFetchMode("children",FetchMode.JOIN );

    	dc.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    	dc.add(Restrictions.eq("cno", parentEventId));
    	
    	List<CICategory> list = getHibernateTemplate().findByCriteria(dc);
    	
    	if(list!=null && list.size()>0)
    		ciCategory = list.get(0);
    	
    	return ciCategory;
    }
    
    public void findChildrenCno(Category entity,List<Long> cnolist){
    	List<Category> cilist=entity.getChildren();
		if (cilist != null && cilist.size() > 0) {
			for (Category ctg : cilist) {
				cnolist.add(ctg.getCno());
				findChildrenCno(ctg,cnolist);
			}
		}
    }
    
	//获取SLA编号
    public static Long latesCICategoryNo=0L;

    /**
     * 取得最新的编号.
     * @return Long
     */
    public Long getLatesCICategoryNo() {
    	synchronized(this){
    		return latesCICategoryNo;
    	}
	}

    /**
     * 设置值.
     * @param latesCICategoryNo
     */
	public void setLatesCICategoryNo(Long latesCICategoryNo) {
		synchronized(this){
		
			CICategoryDAO.latesCICategoryNo = latesCICategoryNo;
		}
	}


	/**
     * 累加SLA编号.
     */
    public void increment(){
    	synchronized(this){
    		latesCICategoryNo+=1;
    	}
    }
    

    /**
     * 取得下一个编号.
     * @return Long
     */
    @SuppressWarnings("rawtypes")
    public Long getNextCICategoryNo(){
    	Long v = 1L;
    	final String hql = "select max(ec.cno) from Category ec";
    	List list=getHibernateTemplate().find(hql);
    	
    	if(list!=null && list.size()>0){
    		Number n = (Number)list.get(0);
    		if (n!=null) {
    			v = n.longValue()+1;
    		}
    	}
    	return v;
    }
    
    /**
     * 获取扩展名称
     * @return Long
     */
    @SuppressWarnings("rawtypes")
    public String getFindEavEntity(String eavNo){
    	String v = "";
    	final String hql = "select ee.eavName from EavEntity ee where ee.eavNo="+eavNo;
    	List list=getHibernateTemplate().find(hql);
    	
    	if(list!=null && list.size()>0){
    		String n = (String)list.get(0);
    		if (n!=null) {
    			v = n.toString();
    		}
    	}
    	return v;
    }
    
    /**
     * 重写SAVE方法.
     */
     @Override
     public void save(CICategory entity){
     	
     	if(entity.getCno()==null || entity.getCno()==0){
     		
     		entity.setCno(getLatesCICategoryNo());
     		
     	}else{
     		
     		if(entity.getCno()>getLatesCICategoryNo()){
     			
     			setLatesCICategoryNo(entity.getCno());
     		}
     		
     	}
     	
     	super.save(entity);
     	increment();//自增1.
     	
     }
     
     @Override
     public CICategory merge(CICategory entity){
    	 
    	if(entity.getCno()!=null){
      		if(entity.getCno()>=getLatesCICategoryNo()){
      			setLatesCICategoryNo(entity.getCno()+1);
      		}
      	}else{
      		increment();//自增1.
    	}
    	 
    	 return super.merge(entity);
     }
    
     /**
      * 判断分类是否存在
      * @param ec
      * @return
      */
     @SuppressWarnings("unchecked")
     public boolean isCategoryExisted(CategoryDTO dto) {
         
         final DetachedCriteria dc = DetachedCriteria.forClass(CICategory.class);
         dc.add(Restrictions.eq("parent.cno", dto.getParentNo()));
         dc.add(Restrictions.eq("cname", dto.getCname()));
         List<CICategory> categories = getHibernateTemplate().findByCriteria(dc);
         
         return !categories.isEmpty();
         
     }
     
     /**
      * 根据Path路径查询子分类
      * @param path 分类路径
      * @return 返回当前路径下的所有分类
      */
 	@SuppressWarnings("unchecked")
	public List<CICategory> findSubCategoryByPath(String path) {
 		final DetachedCriteria dc = DetachedCriteria.forClass(CICategory.class);
 		dc.add(Restrictions.like("path", path, MatchMode.START));
 		return super.getHibernateTemplate().findByCriteria(dc);
 	}
 	/**
 	 * 查找分类，如果该分类不存在，则使用默认分类：配置项分类
 	 * @param no
 	 * @return
 	 */
 	public CICategory findCICategoryById(final Long no ) {
 		CICategory ciCategory = null;
 		if( no != null ){
 			ciCategory = findById(no);
 		}
 		if( ciCategory == null || ciCategory.getCno() == null){
 			ciCategory = findUniqueBy("categoryRoot", "CICategory");
 		}
 		return ciCategory;
 	}
 	/**
     * 根据Path路径查询子分类
     * @param path 分类路径
     * @return 返回当前路径下的所有分类
     */
	@SuppressWarnings("unchecked")
	public List<CICategory> findEavEntity(Long[] eavNos) {
		final DetachedCriteria dc = DetachedCriteria.forClass(CICategory.class);
		dc.add(Restrictions.in("categoryType", eavNos));
		return super.getHibernateTemplate().findByCriteria(dc);
	}
}
